package com.demon.androidbasic.base

import android.app.Application
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.demon.net.*
import com.demon.net.handler.DefaultResponseResultHandler
import com.demon.net.handler.IResponseResultHandler
import com.demon.net.handler.IResponseResultHandlerCreator
import com.demon.net.ui.UIState
import kotlinx.coroutines.launch

/**
 * ViewModel 基类
 * <p/>
 *
 * 封装App内ViewModel公用的方法
 *
 * @author zhaozeyang
 * @date 2020/10/15
 */
open class BaseAndroidViewModel(context: Application) : AndroidViewModel(context),
  IRemoteServiceInvoke,IResponseResultHandlerCreator {

  protected val mExecutor  = AppResponseExecutor()
  protected val _uiStateLiveData = MutableLiveData<UIState>()
  val uiStateLiveData: LiveData<UIState> = _uiStateLiveData

  val mResponseResultHandler by lazy { createResponseResultHandler() }

  override fun createNetExecutor(): IExecutor = AppResponseExecutor()
  override fun <T : Any> rpcExecute(
    rpcCall: suspend () -> IAppResponse<T>,
    uiState: MutableLiveData<UIState>,
    responseResultHandler: IResponseResultHandler?,
    success: ((t: T?) -> Unit)?
  ) {
    executeDefault {
      val result = mExecutor.executeRequest(call = {
        rpcCall.invoke()
      })
      if (result is ResponseResult.Success) {
        success?.invoke(result.data)
      } else {
        responseResultHandler?.handle(uiState, result)
      }
    }
  }

  override fun createResponseResultHandler() = DefaultResponseResultHandler()


  private fun executeDefault(func: suspend () -> Unit) {
    viewModelScope.launch {
      func.invoke()
    }
  }

}